import React, { Component } from 'react'
import {Form, Input, Radio, Select, Icon, Button, Card} from 'antd'
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;

class UserAdd extends Component {
  constructor(props) {
    super(props)
    this.state = {
      editPsd: false
    }
  }

  handleConfirmBlur = (e) => {
    const value = e.target.value;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  }

  handleCheckPassword = (rule, value, callback) => {
    const form = this.props.form;
    if (value && value !== form.getFieldValue('password')) {
      callback('两次输入密码不一致');
    } else {
      callback();
    }
  }

  handleCheckConfirm = (rule, value, callback) => {
    const form = this.props.form;
    if (value && this.state.confirmDirty) {
      form.validateFields(['confirm'], { force: true });
    }
    callback();
  }

  //验证账号是否重名
  handleCheckUser = (rule, value, callback) => {
    const form = this.props.form;
    this.props.checkUser({userName: value}).then(res => {
      if(res.status !== 200){
        callback(res.err);
      } else {
        callback();
      }
    })
  }

  //点击修改密码
  handleEditPsd = () => {
    this.setState({
      editPsd: !this.state.editPsd,
    })
  }

  //取消
  handleCancel = () => {
    const { onCancel, form } = this.props;
    onCancel();
    form.resetFields();
    this.setState({
      editPsd: false,
    })
  }

  //提交修改、创建
  handleCreate = (e) => {
    e.preventDefault();
    const {defaultValues, form, onSubmit } = this.props;
    const { validateFields } = form;
    validateFields((err, values) => {
      if ( !err) {
        if(defaultValues.userId) {
          values.userId = defaultValues.userId
        }
        /*onCreate(values).then(() => {
          form.resetFields();
        });*/
        if(values.confirm){
          delete(values.confirm);
        }
        onSubmit(values)
      }
    });
  }

  render() {
    const { onCancel, defaultValues, form } = this.props;
    const { editPsd } = this.state;
    const addStatus = defaultValues.userId ? false : true;
    const { getFieldDecorator } = form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    return (
      <Card title={addStatus ? '新增用户' : '修改用户信息'}
            extra={addStatus ? "" : <a onClick={this.handleEditPsd}>
                     {!editPsd?<Icon type="edit"/>: null}
                     <span>{`${editPsd? '取消' : ''}修改密码`}</span>
                   </a>}
            style={{maxWidth: 600, marginTop: 20}}>
        <Form onSubmit={this.handleCreate}>
          <FormItem label="账号" {...formItemLayout} hasFeedback>
            {addStatus ?
            getFieldDecorator('userName', {
              rules: [{
                required: true, message: '账号不能为空'
              }, {
                validator: this.handleCheckUser,
              }, {
                max: 30,
                message: '最大长度不超过30'
              }]
            })(
                <Input placeholder="请输入账号"/>
            ) :
                <div style={{paddingLeft: 6}}>{ defaultValues.userName }</div>
            }
          </FormItem>
          {addStatus || editPsd ?
          <FormItem label={addStatus? "密码" : "新密码"} {...formItemLayout} hasFeedback>
            {getFieldDecorator('password', {
              rules: [{
                required: true, message: '密码不能为空',
              }, {
                min: 6,
                message: '密码长度必须大于6位'
              }, {
                max: 50,
                message: '最大长度不超过50'
              }, {
                pattern: /^(?![^a-zA-Z]+$)(?!\D+$)/,
                message: '密码必须包含字母和数字'
              }, {
                validator: this.handleCheckConfirm,
              }],
            })(
                <Input type="password" placeholder="请输入密码"/>
            )}
          </FormItem>: null}
          {addStatus || editPsd ?
          <FormItem
              {...formItemLayout}
              label="确认密码"
              hasFeedback
              >
            {getFieldDecorator('confirm', {
              rules: [{
                required: true, message: '确认密码不能为空',
              }, {
                validator: this.handleCheckPassword,
              }],
            })(
                <Input type="password" placeholder="请再次输入密码"
                       onBlur={this.handleConfirmBlur} />
            )}
          </FormItem> : null }
          <FormItem label="联系人手机" {...formItemLayout} hasFeedback>
            {getFieldDecorator('phone', {
              rules: [{
                required: true, message: '手机号码不能为空',
              }, {
                pattern:/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/,
                message: '请输入正确的手机号码'
              }],
              initialValue: defaultValues.phone || '' ,
            })(
                <Input placeholder="请输入联系人手机"/>
            )}
          </FormItem>
          <FormItem label="联系人邮箱" {...formItemLayout} hasFeedback>
            {getFieldDecorator('email', {
              rules: [{
                type: 'email', message: '请输入正确格式的邮箱号码',
              }, {
                required: true, message: '邮箱号码不能为空'
              }, {
                max: 100,
                message: '最大长度不超过100'
              }],
              initialValue: defaultValues.email || '' ,
            })(
                <Input placeholder="请输入联系人邮箱"/>
            )}
          </FormItem>
          <FormItem label="状态" {...formItemLayout}>
            {getFieldDecorator('status', {
              initialValue: defaultValues.status === undefined ? '1' : defaultValues.status + '' ,
            })(
                <RadioGroup>
                  <Radio value="1">启用</Radio>
                  <Radio value="0">禁用</Radio>
                </RadioGroup>
            )}
          </FormItem>
          <FormItem label=" " colon={false} {...formItemLayout}>
            <Button onClick={onCancel}>返回</Button>
            <Button type="primary" htmlType="submit" style={{marginLeft: 10}} >
              {addStatus ? "创建" : "保存"}
            </Button>
          </FormItem>
        </Form>
      </Card>
    )
  }
}

export default Form.create()(UserAdd);
